package com.insight.common.util;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.yuanqiao.insight.common.constant.CommonConstant;
import com.yuanqiao.insight.common.util.common.LocalCacheUtils;
import com.yuanqiao.insight.common.util.common.RedisUtils;
import lombok.extern.slf4j.Slf4j;
import com.insight.common.constant.MPConstant;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * 小程序获取token
 * @author JinPengDong
 * @date 2023/1/12
 */
@Slf4j
@Component
public class MPRefreshTokenUtil {

    @Autowired
    private RedisUtils redisUtils;
    LocalCacheUtils cacheUtils = LocalCacheUtils.getInstance();

    public void getAccessToken() {
        String appid = cacheUtils.getValueByKey(CommonConstant.DATA_DICT_KEY + "mp_appid") + "";
        String appSecret = cacheUtils.getValueByKey(CommonConstant.DATA_DICT_KEY + "mp_appSecret") + "";

        if (Boolean.FALSE.equals(redisUtils.hasKey(MPConstant.ACCESS_TOKEN_KEY))) {
            HttpRequest get = HttpUtil.createGet(String.format("https://api.weixin.qq.com/cgi-bin/token?grant_type=%s&appid=%s&secret=%s", MPConstant.CLIENT_CREDENTIAL, appid, appSecret));
            HttpResponse execute = get.execute();
            String body = execute.body();
            JSONObject res = JSON.parseObject(body);
            String accessToken = res.getString("access_token");
            //Integer expiresIn = res.getInteger("expires_in");
            //token保存时间改为1小时
            redisUtils.set(MPConstant.ACCESS_TOKEN_KEY, accessToken, 60 * 60);
            log.info("");
        }
    }
}
